<template>
  <div class="app-container">
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="170px"
      class="demo-ruleForm"
    >
      <el-form-item label="姓名" prop="name">
        <el-input class="input" :maxlength="10" v-model="ruleForm.name" placeholder="输入姓名"></el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input class="input" :maxlength="11" v-model="ruleForm.mobile" placeholder="输入手机号"></el-input>
      </el-form-item>
      <el-form-item label="身份证号" prop="idCardNum">
        <el-input class="input" :maxlength="18" v-model="ruleForm.idCardNum" placeholder="输入身份证号"></el-input>
      </el-form-item>
      <el-form-item label="银行卡号" prop="bankNum">
        <el-input class="input"  :maxlength="20" v-model="ruleForm.bankNum" placeholder="输入银行卡号"></el-input>
      </el-form-item>
      <el-row>
        <el-col :span="6">
          <el-form-item label="上传身份证正反面照片" prop="idCardFont">
            <TheUpload
              ref="idCardRefs"
              :files="ruleForm['idCardFont']"
              :limit="1"
              @upload="
                (e) =>
                  (ruleForm['idCardFont'] = e.files.map((file) => file.url))
              "
            />
            <span>上传身份证正面照片</span>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label prop="idCardBack" label-width="0">
            <TheUpload
              ref="idCardRefs"
              :files="ruleForm['idCardBack']"
              :limit="1"
              @upload="
                (e) =>
                  (ruleForm['idCardBack'] = e.files.map((file) => file.url))
              "
            />
            <span>上传身份证反面照片</span>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="上传学习证明资料/相关经验证明资料(最多8张)" prop="studyImages">
        <TheUpload
          ref="studyRefs"
          :files="ruleForm['studyImages']"
          :limit="8"
          @upload="
            (e) => (ruleForm['studyImages'] = e.files.map((file) => file.url))
          "
        />
      </el-form-item>
      <el-form-item label="是否有实体店" prop="isStore">
        <el-radio-group v-model="ruleForm.isStore">
          <el-radio label="YES">是</el-radio>
          <el-radio label="NO">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="所在地址" prop="address" v-if="ruleForm.isStore === 'YES'">
        <span @click="onChooseMap">
          <el-input :readonly="true"    style="width: 400px" v-model="ruleForm.address"></el-input>
        </span>
        <ChooseMap ref="mapChooseRefs" :isDialog="true" @confirm="onMapConfirm" />
      </el-form-item>
      <el-form-item label="门头照" prop="storeImage" v-if="ruleForm.isStore === 'YES'">
        <TheUpload
          ref="storeImageRefs"
          :files="ruleForm['storeImage']"
          :maxLength="8"
          @upload="onUpload"
        />
      </el-form-item>
      <h2>服务区域信息</h2>
      <p>订单将按照“重点服务区域”、“优先服务区域”、”普通服务区域“的顺序派单</p>
      <el-form-item label="重点服务区域(1个)" prop="emphasis">
        <el-cascader
          clearable
          :props="{ ...props, multiple: true }"
          v-model="ruleForm.emphasis"
          style="width: 400px"
          placeholder="选择重点服务区域"
        ></el-cascader>
      </el-form-item>
      <el-form-item label="优先服务区域(2个)" prop="priority">
        <el-cascader
          clearable
          :props="{ ...props, multiple: true }"
          v-model="ruleForm.priority"
          style="width: 400px"
          placeholder="选择优先服务区域"
        ></el-cascader>
      </el-form-item>
      <el-form-item label="普通服务区域(最多3个)" prop="common">
        <el-cascader
          clearable
          :props="{ ...props, multiple: true, field: 'common' }"
          v-model="ruleForm.common"
          style="width: 400px"
          placeholder="选择普通服务区域"
        ></el-cascader>
      </el-form-item>
      <el-form-item label="服务品类" prop="cates">
        <el-checkbox-group v-model="ruleForm.cates">
          <el-checkbox
            style="width: 250px;margin:0 10px 10px 0"
            :label="item"
            border
            v-for="item in cateData"
            :key="item.categoryId"
          >{{ item.categoryName }}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">新建师傅</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import TheUpload from "@/components/TheUpload";
import ChooseMap from "@/components/Map/chooseMap.vue";

import { apiCommonDistrict, apiWorkerCreate } from "@/api/worker.js";
import {
  apiServiceCategoryTree,
  apiServiceCategoryList
} from "@/api/serviceCategory.js";
import {
  validatePhone,
  validateRealName,
  validateIdNumber
} from "@/utils/validate";
export default {
  components: { TheUpload, ChooseMap },
  data() {
    const _this = this;
    return {
      cateData: [],
      ruleForm: {
        name: "",
        mobile: "",
        idCardNum: "",
        bankNum: "",
        idCardFont: [],
        idCardBack: [],
        studyImages: [],
        isStore: "",
        address: "",
        storeImage: [],
        emphasis: [],
        priority: [],
        common: [],
        cates: []
      },
      rules: {
        name: [
          { required: true, message: "请输入姓名", trigger: "blur" },
          { validator: validateRealName, trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "change" },
          { validator: validatePhone, trigger: "blur" }
        ],
        idCardNum: [
          { required: true, message: "请输入身份证号", trigger: "change" },
          { validator: validateIdNumber, trigger: "blur" }
        ],
        bankNum: [
          { required: true, message: "请输入银行卡号", trigger: "change" }
        ],
        idCardFont: [
          {
            type: "array",
            required: true,
            message: "请上传身份证人像面",
            trigger: "change",
            len: 1
          }
        ],
        idCardBack: [
          {
            type: "array",
            len: 1,
            required: true,
            message: "请上传身份证国徽面",
            trigger: "change"
          }
        ],
        studyImages: [
          {
            type: "array",
            required: true,
            message: "请上传上传学习证明资料/相关经验证明资料",
            trigger: "change"
          }
        ],
        isStore: [
          {
            required: true,
            message: "请选择是否有实体店",
            trigger: "change"
          }
        ],
        storeImage: [
          {
            required: true,
            message: "请上传门头照",
            trigger: "change"
          }
        ],
        emphasis: [
          {
            required: true,
            message: "请选择重点服务区域",
            trigger: "change"
          },
          {
            len: 1,
            type: "array",
            message: "请选择1个重点服务区域",
            trigger: "blur"
          }
        ],
        priority: [
          {
            required: true,
            message: "请选择优先服务区域",
            trigger: "change"
          },
          {
            len: 2,
            type: "array",
            message: "请选择2个优先服务区域",
            trigger: "blur"
          }
        ],

        cates: [
          {
            type: "array",
            required: true,
            message: "请选择服务品类",
            trigger: "change"
          }
        ]
      },
      props: {
        lazy: true,
        value: "items",
        async lazyLoad(node, resolve) {
          console.log(node, "nodes");
          let field = "";
          if (node.level > 0) {
            field = node.config.field;
          }

          const nodes = await _this.getDistrict(
            node.level > 0 ? node.value.id : 0,
            field
          );
          resolve(nodes);
        }
      }
    };
  },
  watch: {
    "ruleForm.emphasis": {
      deep: true,
      handler(nVal, oVal) {
        if (nVal.length >= 2) {
          this.$message.warning("最多只支持选择1项");
          this.$nextTick(() => {
            this.ruleForm.emphasis = oVal;
          });
        }
      }
    },
    "ruleForm.priority": {
      deep: true,
      handler(nVal, oVal) {
        if (nVal.length >= 3) {
          this.$message.warning("最多只支持选择2项");
          this.$nextTick(() => {
            this.ruleForm.priority = oVal;
          });
        }
      }
    },
    "ruleForm.common": {
      deep: true,
      handler(nVal, oVal) {
        if (nVal.length >= 4) {
          this.$message.error("最多只支持选择3项");
          this.$nextTick(() => {
            this.ruleForm.common = oVal;
          });
        }
      }
    }
  },
  mounted() {
    this.getCateData();
  },
  methods: {
    onChooseMap() {
      this.$refs.mapChooseRefs.open();
    },
    onMapConfirm(info) {
      this.ruleForm.address = info.name + info.address;
      this.ruleForm.addressLat = info.lat;
      this.ruleForm.addressLnt = info.lng;
    },
    onUpload(e) {
      console.log(e, "e");
      this.ruleForm.storeImage = e.files.map(item => item.url);
    },
    getCateData() {
      apiServiceCategoryList({ categoryLevel: 2 }).then(res => {
        this.cateData = res.data;
      });
    },
    getDistrict(pid, field) {
      return new Promise((resolve, reject) => {
        apiCommonDistrict({ pid })
          .then(res => {
            resolve(
              res.data.map(item => {
                return {
                  value: item.id,
                  items: item,
                  label: item.name,
                  type: item.level,
                  leaf:
                    field && field === "common"
                      ? item.level == "area"
                      : item.level == "street"
                };
              })
            );
          })
          .catch(err => {
            reject([]);
          });
      });
    },
    submitForm(formName) {
      console.log(this.ruleForm);
      this.$refs[formName].validate(valid => {
        if (valid) {
          const { ruleForm } = this;
          const areas = [];
          ruleForm.emphasis.forEach(item => {
            let serviceAreaName = "",
              serviceAreaId = "",
              serviceLevel = "IMPORTANT_POINT";
            item.forEach((dd, ii) => {
              serviceAreaName += dd.name;
              if (ii == item.length - 1) {
                serviceAreaId = dd.id;
              }
            });
            areas.push({
              serviceAreaName,
              serviceAreaId,
              serviceLevel
            });
          });
          ruleForm.priority.forEach(item => {
            let serviceAreaName = "",
              serviceAreaId = "",
              serviceLevel = "PRECEDENCE";
            item.forEach((dd, ii) => {
              serviceAreaName += dd.name;
              if (ii == item.length - 1) {
                serviceAreaId = dd.id;
              }
            });
            areas.push({
              serviceAreaName,
              serviceAreaId,
              serviceLevel
            });
          });
          ruleForm.common.forEach(item => {
            let serviceAreaName = "",
              serviceAreaId = "",
              serviceLevel = "ORDINARY";
            item.forEach((dd, ii) => {
              serviceAreaName += dd.name;
              if (ii == item.length - 1) {
                serviceAreaId = dd.id;
              }
            });
            areas.push({
              serviceAreaName,
              serviceAreaId,
              serviceLevel
            });
          });
          const params = {
            workerName: ruleForm.name,
            userPhoneNumber: ruleForm.mobile,
            identityCardNumber: ruleForm.idCardNum,
            bankCardNumber: ruleForm.bankNum,
            identityCardFront: ruleForm.idCardFont.join(","),
            identityCardBack: ruleForm.idCardBack.join(","),
            information: ruleForm.studyImages.join(","),
            storeHistory: {
              storesFlag: ruleForm.isStore,
              storesImageUrl: ruleForm.storeImage.join(","),
              address: ruleForm.address,
              addressLongitude: 126,
              addressLatitude: 94
            },
            area: areas,
            category: ruleForm.cates.map(item => {
              return {
                categoryId: item.categoryId,
                categoryName: item.categoryName
              };
            })
          };
          apiWorkerCreate(params).then(res => {
            this.$message({
              type: "success",
              message: "新建师傅成功"
            });
            this.$router.back();
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    onEmphasisChange(e, a) {
      console.log(e, a);
    }
  }
};
</script>

<style scoped lang="scss">
.input {
  width: 300px;
}
</style>
